import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)

const store = new Vuex.Store({
  // 这里面就可以写核心概念了
  state: {
    // count: localStorage.getItem('count') || 100
    count: 100
  },
  // getters 相当于组件中的computed
  getters: {
    // 这里的state就是上面的state
    doubleCount (state) {
      return state.count * 2
    }
  },
  // 同步
  mutations: {
    /**
     *
     * @param {*} state 上面的state
     * @param {*} payload 参数
     */
    add (state, payload) {
      state.count += payload

      // localStorage.setItem('count', JSON.stringify(state.count))
    },
    minus (state, payload) {
      state.count -= payload

      // localStorage.setItem('count', JSON.stringify(state.count))
    }
  },
  // 异步
  actions: {
    asyncMinus (context, payload) {
      setTimeout(() => {
        context.commit('minus', payload)
      }, 2000)
    }
  },
  plugins: [
    createPersistedState({
      key: 'my-count'
    })
  ]
})

export default store
